package com.wjm.blog.common.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Locale;

/**
 * 国际化消息工具类
 *
 * @author Ailos
 * @version 1.0
 * @date 2020/12/24
 */
@Component
public class MessageUtil {
    @Autowired
    private MessageSource messageSource;

    private static MessageSource staticMessageSource;

    @PostConstruct
    public void init() {
        MessageUtil.staticMessageSource = messageSource;
    }

    public static String getMessage(String messageKey) {
        String message;
        try {
            Locale locale = LocaleContextHolder.getLocale();
            message = staticMessageSource.getMessage(messageKey, null, locale);
        } catch (Exception e) {
            message = messageKey;
        }
        return message;
    }
}
